package com.suyeer.fastwechat.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.suyeer.basic.util.EncryptUtil;
import com.suyeer.basic.util.JsonUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;
import java.util.TreeSet;

import static com.suyeer.fastwechat.util.FwConstUtil.*;

/**
 * @author jun 2018/11/22
 */
public class FwBaseUtil {

    private static Logger logger = LoggerFactory.getLogger(FwBaseUtil.class);

    /**
     * 创建md5摘要,规则是:按参数名称a-z排序,遇到空值的参数不参加签名.
     *
     * @param treeMap TreeMap
     * @param mchKey  String
     * @return String
     */
    public static String createSign(TreeMap<String, String> treeMap, String mchKey) {
        return EncryptUtil.md5(toString(treeMap) + "&key=" + mchKey).toUpperCase();
    }

    public static String createJsSdKSign(TreeMap<String, String> treeMap) {
        return EncryptUtil.sha1(toString(treeMap));
    }

    private static String toString(TreeMap<String, String> treeMap) {
        StringBuffer sb = new StringBuffer();
        for (Map.Entry<String, String> entry : treeMap.entrySet()) {
            if (StringUtils.isNotBlank(entry.getKey())
                    && StringUtils.isNotBlank(entry.getValue())
                    && !"mch_key".equalsIgnoreCase(entry.getKey())) {
                sb.append(String.format("%s=%s&", entry.getKey(), entry.getValue()));
            }
        }
        sb.deleteCharAt(sb.length() - 1);
        return sb.toString();
    }

    /**
     * 参数校验, 对象类型数据, 不能是基本类型数据.
     *
     * @param obj Object
     * @throws Exception Exception
     */
    public static void checkParams(Object obj) throws Exception {
        Boolean flag = false;
        StringBuilder sb = new StringBuilder();
        sb.append("参数校验 :\n");
        HashMap<String, String> params = JsonUtil.changeType(obj, HashMap.class);
        for (Map.Entry<String, String> entry : params.entrySet()) {
            if (StringUtils.isEmpty(entry.getValue())) {
                flag = true;
                sb.append(String.format("\t不合法参数: %s\n", entry.getKey()));
            }
        }
        if (flag) {
            throw new Exception(sb.toString());
        }
    }

    public static long getTimestamp() {
        return System.currentTimeMillis() / 1000;
    }

    public static String checkWxRequest(String paramJsonStr, String token) throws Exception {
        try {
            paramJsonStr = paramJsonStr.replaceAll("\\[|\\]", StringUtils.EMPTY);
            JSONObject obj = JSON.parseObject(paramJsonStr);
            String signature = obj.getString(WX_PARAM_SIGNATURE);
            String timestamp = obj.getString(WX_PARAM_TIMESTAMP);
            String nonce = obj.getString(WX_PARAM_NONCE);
            String echoStr = obj.containsKey(WX_PARAM_ECHO_STR) ? obj.getString(WX_PARAM_ECHO_STR) : StringUtils.EMPTY;
            TreeSet<String> treeSet = new TreeSet();
            treeSet.add(timestamp);
            treeSet.add(nonce);
            treeSet.add(token);
            String tmpStr = StringUtils.join(treeSet.toArray());
            if (!signature.equalsIgnoreCase(EncryptUtil.sha1(tmpStr))) {
                throw new Exception();
            }
            return echoStr;
        } catch (Exception e) {
            throw new Exception("不是来自微信服务器的消息!");
        }
    }
}
